import {Fragment, PureComponent} from 'react';
import {
  Card,
  Popconfirm,
  Form,
  Row,
  Col,
  Input,
  Button,
  message,
  Tag
} from 'antd';
import React from 'react';
import Icon from '@ant-design/icons';
import {connect} from "umi";
import {formatMessage} from "@@/plugin-locale/localeExports";
import ProTable from '@ant-design/pro-table';
import styles from '../common.less';
import {hasPermission, nopermission} from "@/hasPermission";
const { CheckableTag } = Tag;

const tagsData = [
  {
    key: 'USERS',
    value: '用户'
  },
  {
    key: 'Blog',
    value: '博客'
  },
  {
    key: 'Temporary',
    value: '临时文件'
  },
];

class BackFiles extends PureComponent{

  state = {
    formValues: {},
    updateFormValues: {},
    currentPage: 1,
    pageSize: 10,
    selectedTags: []
  }

  columns = [
    {
      title: formatMessage({ id: 'app.backFiles.source' }),
      dataIndex: 'source',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.backFiles.pk' }),
      dataIndex: 'pk',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.backFiles.url' }),
      dataIndex: 'url',
      align: 'center',
      render: text => <a href={text} target='_blank'>{text}</a>
    },
    {
      title: formatMessage({ id: 'app.common.operate' }),
      align: 'center',
      width: '100px',
      render: (text, record) => (
        <Fragment>
          <Popconfirm
          title={formatMessage({ id: 'app.common.confirm-delete' })}
          onConfirm={() => this.deleteRecord(record.url)}
          >
            <a>
              <Icon type='delete' />
              {formatMessage({ id: 'app.common.delete' })}
            </a>
          </Popconfirm>
        </Fragment>
      )
    }
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'backFiles/fetch'
    })
    this.formRef = React.createRef();
  }

  handleBasicTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      currentPage: pagination.current,
      pageSize: pagination.pageSize
    };
    if (sorter.field && sorter.order) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    this.setState({ currentPage: pagination.current, pageSize: pagination.pageSize });
    dispatch({
      type: 'backFiles/fetch',
      payload: params
    });
  };

  handleSearch = e => {
    const { dispatch } = this.props;
    const { selectedTags } = this.state;
    const values = {
      ...e
    };
    values.arr = selectedTags;
    this.setState({
      formValues: values
    });
    if (e == null) {
      values.currentPage = this.state.currentPage;
      values.pageSize = this.state.pageSize;
    } else {
      values.currentPage = 1;
      values.pageSize = 10;
    }
    dispatch({
      type: 'backFiles/fetch',
      payload: values
    });
  };

  handleFormReset = () => {
    const { dispatch } = this.props;
    this.formRef.current.resetFields();
    this.setState({
      formValues: {},
      currentPage: 1,
      pageSize: 10,
      selectedTags: []
    });
    dispatch({
      type: 'backFiles/fetch'
    });
  };

  deleteRecord = url => {
    if (!hasPermission('admin:delete')){
      nopermission();
      return;
    }
    const { dispatch } = this.props;
    dispatch({
      type: 'backFiles/deleteFile',
      payload: {
        url: url
      }
    }).then(res => {
      if (res.status == 200){
        message.success('删除成功！');
        this.handleSearch();
      }
    })
  };

  handleChange = (tag, checked) => {
    const { selectedTags } = this.state;
    const nextSelectedTags = checked ? [...selectedTags, tag] : selectedTags.filter(t => t !== tag);
    this.setState({ selectedTags: nextSelectedTags });
  };

  renderSimpleForm() {
    const { selectedTags } = this.state;

    return (
      <Form ref={this.formRef} onFinish={this.handleSearch}>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={7} sm={24}>
            <Form.Item label={formatMessage({ id: 'app.backFiles.url' })} name='url'>
              <Input />
            </Form.Item>
          </Col>
          <Col md={7} sm={24}>
            <Form.Item label={formatMessage({ id: 'app.backFiles.source' })} name='source'>
              {tagsData.map(tag => (
                <CheckableTag
                  key={tag.key}
                  checked={selectedTags.indexOf(tag.key) > -1}
                  onChange={checked => this.handleChange(tag.key, checked)}
                >
                  {tag.value}
                </CheckableTag>
              ))}
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button style={{ marginLeft: 8 }} type='primary' htmlType='submit'>
                <Icon type='search'/>{formatMessage({ id: 'app.common.query' })}
              </Button>
              <Button
                style={{ marginLeft: 8 }}
                onClick={this.handleFormReset}
                type='primary'
              >
                <Icon type='reload'/>{formatMessage({ id: 'app.common.reset' })}
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      backFiles: {data},
      loading
    } = this.props;

    return (
      <>
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <ProTable
            bordered={true}
            search={false}
            rowKey={record => record.id}
            loading={loading}
            dataSource={data ? data.list : []}
            pagination={data ? data.pagination : {}}
            columns={this.columns}
            onChange={this.handleBasicTableChange}
            options={{
              density: true,
              reload: () => {
                this.handleSearch();
              },
              fullScreen: true,
              setting: true
            }}
          />
        </div>
      </Card>
      </>
    )
  }
}

export default connect(({ backFiles, loading }) => ({
  backFiles,
  loading: loading.effects['backFiles/fetch']
}))(BackFiles);
